package com.liaogui.framework.handler;

import com.liaogui.framework.Invocation;
import com.liaogui.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author liaogui
 * @date 2025/4/16 20:42
 */
public class HttpPostHandler implements HttpHandler{

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response) {
        // 处理服务调用请求 -- invocation对象
        System.out.println("收到post请求:" + request.getRequestURL().toString());
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(request.getInputStream()).readObject();
            System.out.println("请求体:" + invocation);

            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class aClass = LocalRegister.get(interfaceName, invocation.getVersion());

            Method method = aClass.getMethod(methodName, invocation.getParamType());
            String result =  (String) method.invoke(aClass.newInstance(), invocation.getParams());
            IOUtils.write(result, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
